<template>
	<view class="container header">
		    <view class="statusBar" :style="{height:statusBarHeight +'px'}"></view>
			<uni-section class="reward-nav" title="奖罚记录" titleColor="#fff" padding="0rpx">
			  <template v-slot:right>
				<uni-icons type="plusempty"  style="min-height: 70rpx;" color="#FFFFFF"  size="18"  @click="createBut()" v-show=isAddPermission></uni-icons>
			  </template>
			</uni-section>
			<uni-popup ref="popup" type="top" background-color="#fff" borderRadius="40rpx 40rpx 40rpx 40rpx" @change="change"  :style="{top:statusBarHeight+40+'px'}" class="popup-content-out">
				<view class="triangle"></view>
				<view class="popup-content">
					<view class="btn-list-item" @click="createReward()" >					
						<image src="/static/img/reward.png" style="width:30rpx;height:30rpx;top:6rpx"></image>
						<text class="text">新建奖励</text>
					 </view>
					<view class="btn-list-item" style=" border-bottom: 2rpx solid #fff;" @click="createPunishments()">
						<image src="/static/img/punishments.png" style="width:30rpx;height:30rpx;top:6rpx"></image>
						<text class="text">新建惩罚</text>
					</view>
				</view>

			</uni-popup>
		<view>
			<view v-model="activeTab" class ="flex-tab">
				<view :class="['flex-item-V',activeTab==0?'flex-item-V-se':'']" @click="tabChange(0)">奖励</view>
				<view :class="['flex-item-V',activeTab==1?'flex-item-V-se':'']" @click="tabChange(1)">惩罚</view>
			</view>
			<term-picker
			  ref="termPicker"
			  :visable.sync="pickerVisable"
			  :defaultDate="defaultDate"
			  :minYear="1990"
			  :timeLimit="false"
			  :deferYear="100"
			  themeColor="#4e8af7"
			  startText=""
			  endText=""
			  @confirm="dateSelected">
			</term-picker>
			<view class="tab-option">
				
				<view class="tab-option-date tab-option-item" @click="dateOptionClick()">
					 <view class="ellipsis" :class="{ 'view-left':dateOption === 0,'view-left-after':dateOption === 1}">{{dateOptionText}}</view>
					 <view v-if="dateOption === 0" :class="{ 'view-right':dateOption === 0,'view-right-after':dateOption === 1}"><uni-icons type="down" color="rgb(192, 196, 204)"size="15"></uni-icons></view>
					 <view v-if="dateOption === 1" :class="{ 'view-right': dateOption === 0,'view-right-after':dateOption === 1}"><uni-icons type="clear" color="rgb(192, 196, 204)" size="15"  @click.native.stop="dateOptionClear"></uni-icons></view>
				</view>
				
				<view v-if=isAddPermission class="tab-option-user tab-option-item" @click="userOptionClick()">
					<view class="ellipsis" :class="{ 'view-left':userOption === 0,'view-left-after':userOption === 1}">{{userOptionText}}</view>
					 <view v-if="userOption === 0" :class="{ 'view-right':userOption === 0,'view-right-after':userOption === 1}"><uni-icons type="down" color="rgb(192, 196, 204)" size="15"></uni-icons></view>
					 <view v-if="userOption === 1" :class="{ 'view-right': userOption === 0,'view-right-after':userOption === 1}"><uni-icons type="clear" size="15" color="rgb(192, 196, 204)" @click.native.stop="userOptionClear"></uni-icons></view>
				</view>
				<view v-else-if="isAddPermission==false" class="tab-option-user tab-option-item"></view>	
				<tki-tree ref="tkitree"
						  :range="treeData" 
						  :rangeKey="rangeKey" 
						  :foldAll="true"
						  :multiple="true"
						  :selectParent="false"
						  confirmColor="#4e8af7"
						  @confirm="treeConfirm" />	
			</view>
			<scroll-view 
			  :scroll-with-animation="true" 
			  :enable-back-to-top="true"
			  :style="{height: contentHeight+'px'}" 
			  scroll-y="true"
			>
			<view style="margin-top:5rpx" v-if="activeTab === 0">
			  <!-- 奖励列表内容 -->
			  <view class="list-item" v-for="(reward, index) in rewards" :key="index">
				<uni-card :is-shadow="false" is-full>
					<text class="uni-h8">
						 <uni-title type="h2" :title=reward.rewardsDate></uni-title>
					</text>
					<view class="uni-flex uni-row">
						<view class="card-flex-item ">
							<view class="card-flex-item-T">奖励项</view>
							<view class="card-flex-item-V">{{reward.sname}}</view>
						</view>
						<view class="card-flex-item ">
							<view class="card-flex-item-T">奖励对象</view>
							<view class="card-flex-item-V">{{reward.userName}}</view>
						</view>
					</view>
					<view class="uni-flex uni-row">
						<view class="card-flex-item ">
							<view class="card-flex-item-T">奖励金额</view>
							<view class="card-flex-item-V">{{reward.money}}</view>
						</view>
						<view class="card-flex-item ">
							<view class="card-flex-item-T">奖励分数</view>
							<view class="card-flex-item-V">{{reward.rewardScore}}</view>
						</view>
					</view>
					<view class="uni-flex uni-row">
						<view class="card-flex-item ">
							<view class="card-flex-item-T">创建人</view>
							<view class="card-flex-item-V">{{reward.createUserName}}</view>
						</view>
					</view>
					<view class="uni-flex uni-row">
						<view class="card-flex-item ">
							<view class="card-flex-item-T">备注</view>
							<view class="card-flex-item-V">
								<mp-html :content="reward.note" :lazy-load="true"></mp-html>
							</view>
						</view>
					</view>
					<view class="uni-flex uni-row">
						<view class="card-flex-item-T card-flex-last-item">奖励时间: {{reward.createDateTime}}</view>
					</view>
				</uni-card>
			  </view>
			</view>
			<view style="margin-top:5rpx" v-else-if="activeTab === 1">
			    <!-- 惩罚列表内容 -->
			    <view class="list-item" v-for="(punishment, index) in punishments" :key="index">
					<uni-card :is-shadow="false" is-full>
						<text class="uni-h8">
							<uni-title type="h2" :title=punishment.punishmentDate></uni-title>
						</text>
						<view class="uni-flex uni-row">
							<view class="card-flex-item ">
								<view class="card-flex-item-T">惩罚项</view>
								<view class="card-flex-item-V">{{punishment.sname}}</view>
							</view>
							<view class="card-flex-item ">
								<view class="card-flex-item-T">惩罚对象</view>
								<view class="card-flex-item-V">{{punishment.userName}}</view>
							</view>
						</view>
						<view class="uni-flex uni-row">
							<view class="card-flex-item ">
								<view class="card-flex-item-T">惩罚金额</view>
								<view class="card-flex-item-V">{{punishment.money}}</view>
							</view>
							<view class="card-flex-item ">
								<view class="card-flex-item-T">惩罚分数</view>
								<view class="card-flex-item-V">{{punishment.punishmentScore}}</view>
							</view>
						</view>
						<view class="uni-flex uni-row">
							<view class="card-flex-item ">
								<view class="card-flex-item-T">创建人</view>
								<view class="card-flex-item-V">{{punishment.createUserName}}</view>
							</view>
						</view>
						<view class="uni-flex uni-row">
							<view class="card-flex-item ">
								<view class="card-flex-item-T">备注</view>
								<view class="card-flex-item-V">
									<mp-html :content="punishment.note" :lazy-load="true"></mp-html>
								</view>
							</view>
						</view>
						<view class="uni-flex uni-row">
							<view class="card-flex-item-T card-flex-last-item">惩罚时间: {{punishment.createDateTime}}</view>
						</view>
					</uni-card>
			    </view>
			</view>
		</scroll-view>
		</view>  
	</view>
		
</template>

<script>
	import tkiTree from "@/components/tki-tree/tki-tree.vue"
	import termPicker from '@/components/term-picker/term-picker.vue'
	import { padStartDateTime, padEndDateTime,getDefaultDate} from '@/utils/dateUtils.js';

	export default {
		components: {
			tkiTree,
			termPicker
		  },
		data() {
			return {
			  statusBarHeight:0,
			  contentHeight:0,
			  dateOption:0,
			  userOption:0,
			  userIds:[],
			  dateOptionText:'创建日期',
			  userOptionText: '奖励对象',
			  optionStartTime:'',
			  optionEndTieme:'',
			  defaultDate: getDefaultDate(), 
			  pickerVisable:false,
			  treeData:[],
			  rangeKey:"name",
			  userId:'',
			  isAddPermission:true,
			  type: 'right',
			  activeTab: 0, // 默认显示奖励列表
			  rewards: [], // 示例奖励列表数据
			  punishments: [] // 示例惩罚列表数据
			}
		},
		mounted(){
			this.$nextTick(() => {
			   const systemInfo = uni.getSystemInfoSync();
			   this.statusBarHeight = systemInfo.statusBarHeight;
			   this.calculateContentHeight();
			});
			uni.onWindowResize(() => {
			  this.calculateContentHeight();
			});
			const storageData = uni.getStorageSync('userInfo');
			this.userId =storageData.userId;
			this.isAddPermission= storageData.isAdmin ===1?true:false;
			this.refreshDataList();
			this.$myRequest.getRequest("/api/dept/getDepartmentsWithUsers", {userId:storageData.userId}).then(res => {
				this.treeData=res;
			}).catch(res => { 
				uni.showToast({
				  title: '获取部门和用户失败!',
				  icon: 'none'
				});
			});
		},
		methods: {
			calculateContentHeight() {
			  const systemInfo = uni.getSystemInfoSync();
			  this.contentHeight = systemInfo.windowHeight - systemInfo.statusBarHeight - 185;
			},
			clearUserParam(){
				this.userOptionText = this.activeTab===0?'奖励对象':'惩罚对象';
				this.userOption=0;
				this.userIds=[];
				this.refreshDataList();
				const copiedArray = [...this.treeData];
				this.treeData =copiedArray;
			},
			clearDateParam(){
				this.$refs.termPicker._reset(getDefaultDate());
				this.dateOptionText='创建日期';
				this.dateOption=0;
				this.optionStartTime='';
				this.optionEndTime ='';
				this.pickerVisable = false
				this.refreshDataList();
			},
			userOptionClear(event){
				this.clearUserParam();
				event.stopPropagation();
			},
			dateOptionClear(event){
				this.clearDateParam();
				event.stopPropagation();
			},
			dateSelected(e){
				if (Array.isArray(e) || e.length > 0) {
					this.dateOption = 1;
					this.optionStartTime = e[0];
					this.optionEndTime = e[1];
					let newStartStr = e[0].replace(/-/g, '/');
					let newEndStr = e[1].replace(/-/g, '/');
					this.dateOptionText= newStartStr+"-"+newEndStr
					this.refreshDataList();
				}
			},
			treeConfirm(e) {
				if (e.length == 0) {
					this.userOption = 0;
					this.userIds = [];
					return;
				}
				const userNames=[];
				e.forEach(user => {
				    this.userIds.push(user.id);
					userNames.push(user.name);
				});
				this.userOptionText= userNames.join(",");
				this.userOption=1;
				this.refreshDataList();
			},
			dateOptionClick(){
				this.pickerVisable=true;
			},
			userOptionClick(){
				this.$refs.tkitree._show();
			},
			showSuccessMessage(){
				// 显示成功提示信息的逻辑...
				uni.showToast({
					title: '新建成功',
					icon: 'success'
				});
			},
			refreshDataList(){
				const data={
					userId:this.userId,
					startTime:padStartDateTime(this.optionStartTime),
					endTime:padEndDateTime(this.optionEndTime),
					userIds:this.userIds
				}
				if(this.activeTab === 0){
					this.$myRequest.postRequest("/api/rewards/gerRewardsList", data).then(res => {
						  if(res.statusCode===200){
							this.rewards =res.data;
						  }
					}).catch(res => {
					});
				}else{
					this.$myRequest.postRequest("/api/punishments/getPunishmentsList",data).then(res => {
						if(res.statusCode===200){
							this.punishments =res.data;
						}
					});
				}
				
			},
			tabChange(e) {
				this.activeTab =e;
				this.clearDateParam();
				this.clearUserParam();
				this.refreshDataList();
			},
			createBut(){
				this.$refs.popup.open('right')
			},
			change(e) {
				// console.log('当前模式：' + e.type + ',状态：' + e.show);
			},
			createReward(){
				const $this =this;
				this.$refs.popup.close()
				uni.navigateTo({
					// 注意：这里的路径应与 pages.json 中的配置一致
					url: '/pages/tab4/addReward',
				    events: {
					 // 注册一个名为 'addRewardCallback' 的事件监听器
					 addRewardCallback: function(data) {
					    // 执行当前页面的方法或逻辑
						$this.activeTab=0;
						$this.clearDateParam();
						$this.clearUserParam();
						$this.refreshDataList();
						$this.showSuccessMessage();
					 }
				   },
				});    
			},
			createPunishments(){
				const $this =this;
				this.$refs.popup.close()
				uni.navigateTo({
					// 注意：这里的路径应与 pages.json 中的配置一致
					url: '/pages/tab4/addPunishment',
				    events: {
					 // 注册一个名为 'addPunCallback' 的事件监听器
					  addPunCallback: function(data) {
					   // 执行当前页面的方法或逻辑
					    $this.activeTab=1;
					    $this.clearDateParam();
					    $this.clearUserParam();
						$this.refreshDataList();
						$this.showSuccessMessage();
					 }
				   },
				}); 
			}
		}
	}
</script>

<style scoped>
	.container {
	  overflow-x: hidden;
	  display: flex;
	  flex-direction: column;
	  min-height: 100vh; 
	  background-color: #F3F3F3;
	  height: 100%;
	  width: 100vw;
	}
	.uni-flex{
		 display: flex;
	}
	.card-flex-item {
		width: 100%;
		text-align: center;
		flex-direction: row;
	}
	.card-flex-last-item{
		display: flex;
		justify-content: flex-end; 
		margin-right: 30rpx;
	}
	.card-flex-item-T {
		width: 100%;
		height: 150rpx;
		text-align: left;
		font-size: 14px;
		color: #878282;
		height: 50upx;
		line-height: 50upx;
	}
	.card-flex-item-V {
		white-space: nowrap;
		overflow: hidden; 
		text-overflow: ellipsis;   
		width: 100%;
		height: 150rpx;
		text-align: left;
		font-size: 14px;
		flex: 1;
		min-height: 50upx;
		line-height: 50upx;
		height:auto;
		color: #333;
		font-weight: 700;
	}
	 
	.uni-tabs {
	  margin-bottom: 20rpx;
	}
	 
	.tab-content {
	  flex: 1;
	  overflow-y: auto;
	}
	 
	.list-item {
	  padding: 10rpx 16rpx;
	}
	
	.flex-tab {
		display: flex;
		justify-content: center;
		width: 100%;
		background-color: #FFFFFF;
	}
	.flex-item {
		width: 100%;
		height: 200rpx;
		text-align: center;
		line-height: 200rpx;
		flex-direction: row;
	}
	.flex-item-V {
		width: 100%;
		text-align: center;
		font-size: 14px;
		font-weight: 800;
		flex: 1;
		color: #C9C9C9;
		height: 68rpx;
		line-height: 68rpx;
	}
	
	.flex-item-V-se{
		color: #5BA7FF;
		border-bottom: 6upx solid #5BA7FF;
	}


	@mixin flex {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
	}
	
	@mixin height {
		/* #ifndef APP-NVUE */
		height: 100%;
		/* #endif */
		/* #ifdef APP-NVUE */
		flex: 1;
		/* #endif */
	}
	
	.box {
		@include flex;
	}
	.btn-list-item {
	  font-size: 14px;
	  padding: 5rpx;
	  border-bottom: 2rpx solid #ddd;
	}
	.uni-transition{
		position: relative !important;
	}
	.popup-content-out{
		display: flex;
	}
	.triangle {
		top: -14rpx;
		position: absolute;
		right: 10px;
		width: 0;
		height: 0;
		border-left: 16rpx solid transparent;
		border-bottom: 16rpx solid #FFFFFF;
		border-right: 16rpx solid transparent;
	}
	.popup-content {
		@include flex;
		align-items: center;
		justify-content: center;
		padding: 12rpx;
		background-color: #fff;
		position: absolute;
		right: 8px;
	}
	
	.popup-height {
		@include height;
		width: 200rpx;
	}
	
	.text {
		color: #4477C8;
		margin-left: 20rpx;
	}
	
	.reward-nav{
		background-color: #4D71F1;
		min-height:40rpx;
		text-align: center;
	}
	.tab-option{
		font-size: 12px;
		color: #878282;
		padding: 6rpx;
		border-bottom: 1rpx solid #ddd;
		border-top: 1rpx solid #ddd;
		display: flex;
		flex-direction: row;
		background-color: #ffffff;
	    width: 100%;
	}
	.tab-option-item {
	  height: 50rpx;
	  box-sizing: border-box; 
	  flex: 1; 
	  padding: 6px;
	  text-align: center;
	  display: flex;
	  flex-direction: row;
	  align-items: center;
	  justify-content: center; 
	}
	.view-left,.view-right,view-left-after,view-right-after{
		width:100%;
		font-size: 12px;
	}
	.view-left{
		text-align: right;
		flex:6;
		box-sizing: border-box;
		overflow: hidden; 
	}
	.view-right{
		margin-left:3px;
		text-align: left;
		flex:4;
		padding-top:3px;
	}
	.view-left-after{
		text-align: right;
		flex:8;
		box-sizing: border-box;
		overflow: hidden; 
		color:#4477C8;
	}
	.view-right-after{
		margin-left:3px;
		text-align: left;
		flex:2;
		padding-top:3px;
	}
	.ellipsis {
	  /* 文本溢出样式 */
	  white-space: nowrap; /* 禁止文本换行 */
	  overflow: hidden; /* 隐藏溢出内容 */
	  text-overflow: ellipsis; /* 使用省略号表示溢出内容 */
	  display: block; /* 确保省略号能正确显示（在某些情况下可能必需） */
	}
</style>
